<template>
  <div>
    <div class="clearfix">
      <div>
        <!-- 顶部进度 -->
        <edit-task-title ref="editTaskTitle"></edit-task-title>
        <!-- 任务类型 -->
        <edit-task-type ref="editTaskType" :taskId="taskId" :categoryId="oneCategoryId"></edit-task-type>
        <!-- 任务信息 -->
        <edit-task-info ref="editTaskInfo" :taskId="taskId"/>
        <!--需求信息 -->
        <edit-task-need ref="editTaskNeed"/>
        <!--任务要求 -->
        <edit-task-require ref="editTaskRequire"/>

        <!--验收规则 -->
        <edit-task-accept-rule ref="editTaskAcceptRule" :dict="dict"></edit-task-accept-rule>
        <!-- 结算分配 -->
        <edit-task-settlement ref="editTaskSettlement" :dictData="dict"/>
        <!-- 多任务相关 -->
        <edit-task-stage ref="editTaskStage" :dict="dict"></edit-task-stage>
        <!-- 协同任务 -->
        <edit-position-list ref="editPositionList" :dict="dict"></edit-position-list>
      </div>
      <div class="time-line">
        <div class="time-box">
          <!--<time-line :taskId="taskId" :taskType="taskTypeData"></time-line>-->
        </div>
      </div>
    </div>
    <div class="radius-container container-nonebg">
      <el-form label-width="80px">
        <el-button type="primary" @click="saveTask(10)">保存</el-button>
        <el-button type="primary" @click="saveTask(20)">立即发布</el-button>
      </el-form>
    </div>
  </div>
</template>

<script>
  import { getNameByPath } from '@/utils/get-name-by-path' // 不要删除，根据URL获取文件名
  import { saveTaskInfo, getTaskInfoDetail } from '@/api/project/taskInfo'
  import { getDictByGroupName } from '@/api/common/common'
  import elDragDialog from '@/directive/el-dragDialog' // base on element-ui
  import Tinymce from '@/components/Tinymce'
  import EditTaskStage from './components/EditTaskStage'
  import EditTaskType from './components/EditTaskType'
  import EditPositionList from './components/EditPositionList'
  import EditTaskInfo from './components/EditTaskInfo'
  import EditTaskNeed from './components/EditTaskNeed'
  import editTaskRequire from './components/edit-task-require'
  import EditTaskSettlement from './components/EditTaskSettlement'
  import EditTaskAcceptRule from './components/edit-task-accept-rule'
  import EditTaskTitle from './components/edit-task-title'
  import TimeLine from '@/components/Project/TimeLine'

  export default {
    name: getNameByPath(),
    components: {
      Tinymce, EditTaskStage, EditPositionList, EditTaskType, EditTaskInfo, EditTaskNeed,
      EditTaskSettlement, TimeLine, EditTaskAcceptRule, EditTaskTitle, editTaskRequire
    },
    directives: {
      // 拖动窗口
      elDragDialog
    },
    data() {
      return {
        // 传递参数过来的Id
        oneCategoryId: null,
        taskId: null,
        // 数据字典相关>>>>>>>
        categoryId: '',
        validate: {
          success: 1,
          failure: 0
        },
        isSubmit: false,
        activeNum: 1,
        listLoading: false,
        dict: {}
      }
    },
    created() {
      console.log('editMain')
      const queryParams = this.getCurrentPage().query
      const categoryId = queryParams.categoryId
      const taskId = queryParams.taskId
      if (this.$utils.isExist(categoryId)) {
        this.oneCategoryId = categoryId
      }
      if (this.$utils.isExist(taskId)) {
        this.taskId = taskId
      }
      // 加载数据字典
      this.initDict()
    },
    mounted: function() {
      const taskId = this.taskId
      if (taskId !== null) {
        // 初始化数据
        this.initTaskInfo()
      }
    },
    methods: {
      initTaskInfo() {
        const taskId = this.taskId
        getTaskInfoDetail(taskId).then(response => {
          this.$bus.$emit('project.task.edit.taskData', response.data)
        })
      },
      initDict() {
        getDictByGroupName('TaskInfoDTO').then(response => {
          const that = this
          this.dict = response.data
          that.$bus.$emit('task.edit.dict', that.dict)
        })
      },
      checkStage(stageList, budgetAmount) {
        budgetAmount = budgetAmount * 1
        if (budgetAmount === 0) {
          this.$message.error('预算金额不能为0!')
          return this.validate.failure
        }
        let acceptAmountTotal = 0
        stageList.forEach((e) => {
          acceptAmountTotal = acceptAmountTotal + e.acceptAmount * 1
        })
        if (budgetAmount !== acceptAmountTotal) {
          this.$message.error('结算分配金额与预算金额不一致!')
          return this.validate.failure
        }
        return this.validate.success
      },
      checkLevel(levelList, budgetAmount, hireNum) {
        budgetAmount = budgetAmount * 1
        if (budgetAmount === 0) {
          this.$message.error('预算金额不能为0!')
          return this.validate.failure
        }
        let levelAmountTotal = 0
        let levelNumTotal = 0
        levelList.forEach((e) => {
          if (e.levelAmount != null && e.levelAmount !== '') {
            levelAmountTotal = levelAmountTotal * 1 + e.levelAmount * 1
            levelNumTotal = levelNumTotal * 1 + e.levelNum * 1
          }
        })
        if (budgetAmount !== levelAmountTotal) {
          this.$message.error('等级分配金额与预算金额不一致!')
          return this.validate.failure
        }

        if (levelNumTotal * 1 !== hireNum * 1) {
          this.$message.error('录用人数和分配人数总数不相等!')
          return this.validate.failure
        }

        return this.validate.success
      },
      checkTotal(taskInfo) {
        // 悬赏 一人 按阶段
        if (taskInfo.remunerationType === '2' && taskInfo.hireNumType === '1' && taskInfo.settleType === '2') {
          if (this.checkStage(taskInfo.stageList, taskInfo.budgetAmount) === this.validate.failure) {
            return this.validate.failure
          }
        }
        // 悬赏 一人 按等级
        if (taskInfo.remunerationType === '2' && taskInfo.hireNumType === '1' && taskInfo.settleType === '1') {
          if (this.checkLevel(taskInfo.levelList, taskInfo.budgetAmount, 1) === this.validate.failure) {
            return this.validate.failure
          }
        }
        // 协同任务
        if (taskInfo.taskType === 2) {
          const amount = taskInfo.budgetAmount * 1 - taskInfo.leaderAmount * 1
          if (amount === 0) {
            this.$message.error('任务酬金必须大于组长酬金!')
            return this.validate.failure
          }
        }

        // 悬赏 多人 按等级
        if (taskInfo.remunerationType === '2' && taskInfo.hireNumType === '2' && taskInfo.settleType === '1') {
          if (this.checkLevel(taskInfo.levelList, taskInfo.budgetAmount, taskInfo.hireNum) === this.validate.failure) {
            return this.validate.failure
          }
        }
        // 校验计件和人数的关系
        if (taskInfo.remunerationType === 1) {
          const hireNum = taskInfo.hireNum // 人数
          const budgetNum = taskInfo.budgetNum // 计件数量
          if (budgetNum < hireNum) {
            this.$message.error('计件数量要大于人数!')
            return this.validate.failure
          }
        }
        return this.validate.success
      },
      saveTask(taskStatus) {
        let checkRet = true
        checkRet = this.$refs.editTaskType.checkForm()
        if (!checkRet) {
          return
        }
        checkRet = this.$refs.editTaskInfo.checkForm()
        if (!checkRet) {
          return
        }
        const needRet = this.$refs.editTaskNeed.checkForm()
        if (!needRet) {
          return
        }
        const requireRet = this.$refs.editTaskRequire.checkForm()
        if (!requireRet) {
          this.$message.error('微客要求不能为空!')
          return
        }
        const settlementRet = this.$refs.editTaskSettlement.checkForm()
        if (!settlementRet) {
          return
        }

        const taskId = this.taskId
        const enterpriseId = this.getEnterpriseId()
        const twoCategoryId = this.$refs.editTaskType.form.twoCategoryId
        // 计件/悬赏
        const remunerationType = this.$refs.editTaskInfo.form.remunerationType
        // 预算
        const budgetAmount = this.$refs.editTaskInfo.form.budgetAmount
        const taskName = this.$refs.editTaskInfo.form.taskName
        // 悬赏预算类型
        // const budgetType = this.budgetType
        // 是否可以议价
        const bargainingFlag = this.$refs.editTaskInfo.form.bargainingFlag
        // 任务开始周期
        const taskStartTime = this.$refs.editTaskInfo.form.taskStartTime
        // 任务结束周期
        const taskEndTime = this.$refs.editTaskInfo.form.taskEndTime
        // 报名开始时间
        const enrollStartTime = this.$refs.editTaskInfo.form.enrollStartTime
        // 报名结束时间
        const enrollEndTime = this.$refs.editTaskInfo.form.enrollEndTime
        // 任务描述
        const taskDescription = this.$refs.editTaskNeed.form.taskDescription
        // 任务附件列表
        const taskFileList = this.$refs.editTaskNeed.form.fileList
        taskFileList.forEach(taskFile => {
          // 文件提交类型  1：企业提交文件  2：微客提交文件
          taskFile.status = 1
        })

        const requireMemberTypeFlag = this.$refs.editTaskRequire.form.requireMemberTypeFlag
        const requireMemberType = this.$refs.editTaskRequire.form.requireMemberType
        const requireMemberDirectionFlag = this.$refs.editTaskRequire.form.requireMemberDirectionFlag
        const requireAreaFlag = this.$refs.editTaskRequire.form.requireAreaFlag
        const recruitFlag = this.$refs.editTaskRequire.form.recruitFlag
        const onceSign = this.$refs.editTaskRequire.form.onceSign
        const provinceCode = this.$refs.editTaskRequire.form.provinceCode
        const cityCode = this.$refs.editTaskRequire.form.cityCode
        const recruitIds = this.$refs.editTaskRequire.form.recruitIds
        const directionMemberIds = this.$refs.editTaskRequire.form.directionMemberIds

        // 录用人数类型
        const hireNumType = this.$refs.editTaskSettlement.form.hireNumType
        // 内部微客酬金折扣比例
        const internalRatio = this.$refs.editTaskSettlement.form.internalRatio
        // 是否开启内部微客酬金
        const internalRatioFlag = this.$refs.editTaskSettlement.form.internalRatioFlag
        // 录用人数
        let hireNum = this.$refs.editTaskSettlement.form.hireNum

        if (hireNumType === '1') {
          hireNum = 1
        } else {
          if (!this.$utils.isExist(hireNum)) {
            this.$message.error('录用人数不能为空!')
            return
          }
        }
        // 等级
        let levelList = this.$refs.editTaskSettlement.levelList
        // 一次性支付 1 一次性 2 按阶段
        const settleType = this.$refs.editTaskSettlement.form.settleType
        if (settleType * 1 === 1 && hireNum === 1) {
          const oneLevelName = this.$refs.editTaskSettlement.form.oneLevelName
          levelList = [{
            taskType: 1,
            levelName: oneLevelName,
            levelNum: 1,
            levelAmount: budgetAmount,
            sortNo: 1
          }]
        }
        // 分配方式集合
        const payCycleType = this.$refs.editTaskSettlement.form.payCycleType
        let payDay = null
        if (this.$refs.editTaskSettlement.form.payCycleType === '2') {
          payDay = this.$refs.editTaskSettlement.form.payDay1
        }
        if (this.$refs.editTaskSettlement.form.payCycleType === '3') {
          payDay = this.$refs.editTaskSettlement.form.payDay2
        }
        // 阶段
        let stageList = this.$refs.editTaskSettlement.stageList
        // 协同任务
        let leaderAmount = ''
        let positionList = []
        const taskType = this.$refs.editTaskType.form.taskType * 1
        const budgetNum = this.$refs.editTaskInfo.form.budgetNum
        const acceptanceContents = this.$refs.editTaskSettlement.form.acceptanceContents
        const remunerationTypeModel = this.$refs.editTaskInfo.form.remunerationTypeModel
        if (taskType === 2) {
          // 任务酬金
          // budgetAmount = this.$refs.editTaskInfo.form.budgetAmount3
          // 组长酬金
          leaderAmount = this.$refs.editTaskInfo.form.leaderAmount
          // 录用人数
          hireNum = this.$refs.editPositionList.getHireNum()
          positionList = this.$refs.editPositionList.taskPositionList
          // 里程碑设置
          stageList = this.$refs.editTaskStage.getStageList()
          // 任务等级，目前固定一个等级
          levelList = [{
            taskType: 2,
            sortNo: 1,
            levelName: '等级1',
            levelNum: hireNum,
            levelAmount: budgetAmount - leaderAmount
          }]
        }

        // 任务验收规则
        const taskAcceptRuleDTOS = this.$refs.editTaskAcceptRule.dataList
        for (let i = 0; i < taskAcceptRuleDTOS.length; i++) {
          const taskAcceptRuleDTO = taskAcceptRuleDTOS[i]
          if (!this.$utils.isExist(taskAcceptRuleDTO.ruleName) || !this.$utils.isExist(taskAcceptRuleDTO.ruleSettingType)) {
            this.$message.error('验收规则不能为空!')
            return
          }
        }

        const taskInfo = {
          twoCategoryId: twoCategoryId,
          taskType: taskType,
          taskName: taskName,
          // 任务酬金类型 1.计件，2.悬赏
          remunerationType: remunerationType,
          // 酬金模式
          remunerationTypeModel: remunerationTypeModel,
          // 预算金额
          budgetAmount: budgetAmount,
          // 组长酬金
          leaderAmount: leaderAmount,
          // 预算数量
          budgetNum: budgetNum,
          // 是否可以议价
          bargainingFlag: bargainingFlag,
          // 任务开始周期
          taskStartTime: taskStartTime,
          // 任务结束周期
          taskEndTime: taskEndTime,
          // 报名开始时间
          enrollStartTime: enrollStartTime,
          // 报名结束时间
          enrollEndTime: enrollEndTime,
          // 任务描述
          taskDescription: taskDescription,
          // 任务附件列表
          taskFileList: taskFileList,
          // 录用人数类型
          hireNumType: hireNumType,
          // 录用人数
          hireNum: hireNum,
          // 是否一次性支付
          settleType: settleType,
          // 阶段集合
          stageList: stageList,
          // 分配方式集合
          levelList: levelList,
          payCycleType: payCycleType,
          payDay: payDay,
          // 企业Id
          enterpriseId: enterpriseId,
          // 任务状态
          taskStatus: taskStatus,
          // 任务Id
          taskId: taskId,
          // // 单人单阶段名称
          // oneLevelName: oneLevelName,
          positionList: positionList,
          // 内部折扣比例
          internalRatio: internalRatio,
          // 验收标准
          acceptanceContents: acceptanceContents,
          // 是否开启内部微客酬金
          internalRatioFlag: internalRatioFlag ? '1' : '0',
          // 任务规则DTOS
          taskAcceptRuleDTOS: taskAcceptRuleDTOS,
          // 是否开启根据微客类型推送
          requireMemberTypeFlag: requireMemberTypeFlag,
          // 任务类型
          requireMemberType: requireMemberType,
          requireAreaFlag: requireAreaFlag,
          recruitFlag: recruitFlag,
          onceSign: onceSign,
          provinceCode: provinceCode,
          cityCode: cityCode,
          recruitIds: recruitIds,
          directionMemberIds: directionMemberIds,
          requireMemberDirectionFlag: requireMemberDirectionFlag
        }
        const ret = this.checkTotal(taskInfo)
        if (ret === this.validate.failure) {
          return
        }

        // 防重复提交
        if (this.isSubmit) {
          return
        }
        this.isSubmit = true
        saveTaskInfo(taskInfo).then((response) => {
          if (response.isError) {
            this.isSubmit = false
            return
          }
          this.$message({
            type: 'success',
            message: '保存成功!'
          })
          this.$router.push('/project/task/index/')
        })
      }
    }
  }

</script>


<style lang="less" scoped>
  .time-line {
    width: 20%;
    float: left;

    .time-box {
      position: fixed;
      width: 19%;
      right: 0;
      top: 50px;
    }
  }

  .detila-div-80 {
    float: left;
    width: 80%;
  }

  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }

  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }

  .container-nonebg {
    box-shadow: 0 0 0;
    border: none;
  }

  .time-line {
    width: 20%;
    float: left;

    .time-box {
      position: fixed;
      width: 19%;
      right: 0;
      top: 95px;
    }
  }

  .detila-div-80 {
    float: left;
    width: 80%;
  }

  .div-styls {
    margin-top: 30px;
    margin-bottom: 20px;
  }

  .el-tabs__item {
    font-size: 20px;
  }
</style>
